<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<canvas id="webgl" width="500" height="500"></canvas>
<script>
  const gl = document.getElementById('webgl').getContext('webgl');
  const vertexShaderSource = "" +
    "attribute vec4 apos;" +
    "uniform mat4 mat;" +
    "void main(){" +
    " gl_Position = mat * apos;" +
    "}";
  const fragmentShaderSource = "" +
    "void main(){" +
    " gl_FragColor = vec4(1.0,0.0,0.0,1.0);" +
    "}";

  const program = initShader(gl,vertexShaderSource,fragmentShaderSource);
  const aposlocation = gl.getAttribLocation(program,'apos');
  const matlocation = gl.getUniformLocation(program,'mat');

  const data =  new Float32Array([
    0.0,0.0,
    -.3,-.3,
    .3,-.3
  ]);
  const buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER,buffer);
  gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW);

  gl.vertexAttribPointer(aposlocation,2,gl.FLOAT,false,0,0);
  gl.enableVertexAttribArray(aposlocation);

  let Tx = 0.1;    //x坐标的位置
  let Ty = 0.1;    //y坐标的位置
  let Tz = 0.0;    //z坐标的位置
  let Tw = 1.0;    //差值
  function run () {
    Tx += 0.001
    Ty += 0.001
    const mat = new Float32Array([
      1.0,0.0,0.0,0.0,
      0.0,1.0,0.0,0.0,
      0.0,0.0,1.0,0.0,
      Tx,Ty,Tz,Tw,
    ]);
    gl.uniformMatrix4fv(matlocation,false,mat);
    gl.drawArrays(gl.TRIANGLES,0,3);

    // 使用此方法实现一个动画
    requestAnimationFrame(run)
  }
  run()


  function initShader(gl,vertexShaderSource,fragmentShaderSource){
    const vertexShader = gl.createShader(gl.VERTEX_SHADER);
    const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);

    gl.shaderSource(vertexShader,vertexShaderSource);
    gl.shaderSource(fragmentShader,fragmentShaderSource);

    gl.compileShader(vertexShader);
    gl.compileShader(fragmentShader);

    const program = gl.createProgram();

    gl.attachShader(program,vertexShader);
    gl.attachShader(program,fragmentShader)

    gl.linkProgram(program);
    gl.useProgram(program);
    return program;
  }
</script>
</body>
</html>
